package pers.cz.orm.dao.processor;

import pers.cz.common.annotation.Column;
import pers.cz.common.pub.AbstractEntity;
import utils.ObjUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Jef-orm
 * @description: 批量插入处理
 *  批量插入有两种模式
 *  一种为：insert into xx value(?,?) jdbc.batchInset
 *  另一种为oracle模式下的hint方式即，insert +append into value(?,?)
 * @author: Cheng Zhi
 * @create: 2023-09-26 17:26
 **/
public class BatchInsertProcessor extends InsertProcessor {

    private List<AbstractEntity> entities;

    public void setEntitys(List<AbstractEntity> entitys) {
        // 1、组装SQL insert into xxx(c1,c2,c3) values(?,?,?)
        this.entities = entitys;
        setEntity(entities.get(0));
    }

    @Override
    protected String getInsertKeyAndParam() {

        StringBuilder sqlBuilderKey = new StringBuilder();
        StringBuilder sqlBuilderValue = new StringBuilder();
        Map<String, Object> entityInfo = new HashMap<>();
        // 反射执行get方法
        ObjUtils.getFieldNameAndValue(entity, entityInfo);
        Object[] objects = entityInfo.keySet().toArray();
        int commaCount = 0;

        for (int i=0; i<objects.length; i++) {
            commaCount ++;
            if (getIgnores().get(ObjUtils.under2camel((String) objects[i])) != null) {
                continue;
            }
            Column column = getColums().get(ObjUtils.under2camel((String) objects[i]));
            String columnName = column == null? (String) objects[i] : column.name();
            sqlBuilderKey.append(columnName);
            sqlBuilderValue.append("?"); // 批量插入和普通插入的区别就在于，普通的插入这里是实际值，而批量插入这里是占位符

            if (commaCount != objects.length) {
                sqlBuilderKey.append(COMMA);
                sqlBuilderValue.append(COMMA);
            }
        }
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append(LEFT_PAREN);
        sqlBuilder.append(sqlBuilderKey);
        sqlBuilder.append(RIGHT_PAREN);
        sqlBuilder.append(" values ");
        sqlBuilder.append(LEFT_PAREN);
        sqlBuilder.append(sqlBuilderValue);
        sqlBuilder.append(RIGHT_PAREN);

        return sqlBuilder.toString();
    }

}
